package org.finesys.common.core.support.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.finesys.common.constants.BaseConstant;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.WebUtil;
import org.springframework.lang.NonNull;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

/**
 * 拦截器只放行通过网关的请求
 */
public class ServerProtectInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(@NonNull HttpServletRequest request,@NonNull HttpServletResponse response,@NonNull Object handler)
			throws Exception {
		// 获取gatewayToken
		String token = request.getHeader(BaseConstant.GATEWAY_TOKEN_HEADER);

		String gatewayToken = new String(Base64Utils.encode(BaseConstant.GATEWAY_TOKEN_VALUE.getBytes()));
		// 校验正确性
		if (StringUtils.equals(gatewayToken, token)) {
			return true;
		}
		WebUtil.makeFailureResponse(response, R.failed("please get resources through the gateway!"));
		return false;
	}

}
